import { defineStore } from 'pinia';
import axios from 'axios';

// 平台统计数据类型
export interface PlatformStats {
  totalQuestions: number;
  totalAnswers: number;
  totalUsers: number;
  totalCategories: number;
  resolvedRate: number; // 问题解决率 (0-1)
  dailyActiveUsers: number; // 日活跃用户
  questionsPerDay: number; // 日均提问数
}

// 定义Store
export const useStatsStore = defineStore('stats', {
  state: (): {
    stats: PlatformStats;
    loading: boolean;
    error: string | null;
  } => ({
    stats: {
      totalQuestions: 0,
      totalAnswers: 0,
      totalUsers: 0,
      totalCategories: 0,
      resolvedRate: 0,
      dailyActiveUsers: 0,
      questionsPerDay: 0
    },
    loading: false,
    error: null
  }),

  getters: {
    // 格式化数字（如1000 -> 1k）
    formatNumber: () => (num: number): string => {
      if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
      }
      if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'k';
      }
      return num.toString();
    },
    
    // 获取解决率百分比
    resolvedRatePercentage: (state) => {
      return Math.round(state.stats.resolvedRate * 100) + '%';
    }
  },

  actions: {
    // 获取平台统计数据
    async fetchPlatformStats(): Promise<void> {
      try {
        this.loading = true;
        this.error = null;
        const response = await axios.get<PlatformStats>('/api/stats');
        this.stats = response.data;
      } catch (err) {
        this.error = err instanceof Error ? err.message : '获取平台统计数据失败';
        console.error('获取统计数据错误:', this.error);
      } finally {
        this.loading = false;
      }
    },
    
    // 重置统计数据
    resetStats(): void {
      this.stats = {
        totalQuestions: 0,
        totalAnswers: 0,
        totalUsers: 0,
        totalCategories: 0,
        resolvedRate: 0,
        dailyActiveUsers: 0,
        questionsPerDay: 0
      };
    }
  }
});
    